package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Comment;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.service.ICommentService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @descreption:
 * @author: xhr
 * @date: 2022/08/18
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Resource
    CommentMapper commentMapper;
    @Resource
    ICommentService commentService;
    //增
    @PostMapping
    public Result<?> save(@RequestBody Comment comment) {
        comment.setTime(new Date());
        commentMapper.insert(comment);
        return Result.success();
    }
//    // 改
//    @PutMapping
//    public Result<?> update(@RequestBody Comment comment) {
//        commentMapper.updateById(comment);
//        return Result.success();
//    }
    // 删
    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        commentMapper.deleteById(id);
        return Result.success();
    }
    //查某个业务

    @GetMapping("/{newId}")
    public Result<?> findNewComment (@PathVariable Integer newId){
        List<Comment> comments = commentService.list(new QueryWrapper<Comment>().eq("new_id", newId));
        List<Comment> rootComments = comments.stream().filter(comment -> comment.getPid() == null).collect(Collectors.toList());
        for (Comment rootComment : rootComments) {
            rootComment.setChildren(comments.stream().filter(comment -> rootComment.getId().equals(comment.getPid())).collect(Collectors.toList()));
        }
        return Result.success(rootComments);
    }
//    //全查
//    @GetMapping
//    public Result<?> findAll(){
//        return Result.success(
//                commentMapper.selectList(null)
//        );
//    }
    //查
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "10") Integer pagesize,
                              @RequestParam(defaultValue = "1") Integer pagenum,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Comment> wrapper = Wrappers.<Comment>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Comment::getContent, search);
        }
        return Result.success(commentMapper.selectPage(new Page<>(pagenum, pagesize), wrapper));
    }
}
